package com.etop.jansing.controller;

import com.etop.jansing.dto.ResourceDto;
import com.etop.jansing.entities.Permission;
import com.etop.jansing.entities.Resource;
import com.etop.jansing.service.PermissionService;
import com.etop.jansing.service.ResourceService;
import com.etop.jansing.util.CommonUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * Created by jansing on 2015/10/26.
 */
@Controller
@RequestMapping("admin/resource")
@RequiresRoles("admin")
public class ResourceController extends BaseController {

    @javax.annotation.Resource
    private ResourceService resourceService;
    @javax.annotation.Resource
    private PermissionService permissionService;

    /**
     * 注入资源信息。<br/>
     * 这个方法会在请求进入该控制器的某个方法前调用，<br/>
     * 比如修改资源：在进入edit()--POST 前会执行此方法返回一个resource，然后再将表单的数据放入这个resource<br/>
     *
     * @param tempId
     * @return
     */
    @ModelAttribute("resource")
    public Resource get(@RequestParam(required = false, value = "id") String tempId) {
        try {
            Long id = Long.parseLong(tempId);
            if (id != null && id > 0) {
                return resourceService.getById(id);
            } else {
                return new Resource();
            }
        } catch (NumberFormatException e) {
            return new Resource();
        }
    }


    /**
     *
     * @param resource
     * @param model
     * @return
     */
    @RequiresPermissions("resource:list")
    @RequestMapping(value = "/list", produces = "text/html;charset=utf-8")
    public String list(@ModelAttribute("resource") Resource resource, Model model) {
        ResourceDto rootResourceDto = resourceService.getRootResource(null);
        model.addAttribute("rootResourceDto", rootResourceDto);
        return "admin/resource/list";
    }

    @RequiresPermissions("resource:edit")
    @RequestMapping(value = "/edit", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String editResource(Model model, @ModelAttribute("resource") Resource resource) {
        List<Resource> canBeParent = resourceService.getCanBeParentResources(resource);
        List<Permission> permissionList = permissionService.getAllPermissions();
//        该资源已有的资源权限对
        List<Permission> hadPermissionList = permissionService.getByResource(resource);
//        已被角色引用的资源权限对
        List<Permission> beUsingPermissionList = permissionService.getUsingPermission(resource);
        model.addAttribute("resource", resource);
        model.addAttribute("canBeParent", canBeParent);
        model.addAttribute("permissionList", permissionList);
        model.addAttribute("hadPermissionList", hadPermissionList);
        model.addAttribute("beUsingPermissionList", beUsingPermissionList);
        return "/admin/resource/edit";
    }

    @RequiresPermissions("resource:edit")
    @RequestMapping(value = "/edit", produces = "text/html;charset=utf-8", method = RequestMethod.POST)
    public String saveResource(@ModelAttribute(value = "resource") Resource resource, HttpServletRequest request, Model model)
            throws Exception {
        String oldName = request.getParameter("oldName");
        //与已删除的资源也不能同名
        if (!oldName.equals(resource.getName()) &&
                resourceService.getByNameIgnoreValid(resource.getName()) != null) {
            log.error("-->该资源名已存在");
            resource.setName(oldName);
            return editResource(model, resource);
        }
        Long parentId = CommonUtils.getId(request.getParameter("parentId"));
        String[] pids = request.getParameterValues("permissions");
        resourceService.saveOrUpdate(resource, parentId, pids);
        return "redirect:/admin/resource/list";
    }

    /**
     * 如果角色有该资源的资源权限对，则拒绝删除；删除资源的同时删除其资源权限对
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("resource:delete")
    @RequestMapping(value = "/delete/{id}", produces = "text/html;charset=utf-8")
    public String deleteResource(@PathVariable("id") long id, Model model) {
        Resource resource = resourceService.getById(id);
        if (resourceService.isUsing(resource)) {
            //如果某个角色有该资源的某个权限，即为被占用，此时不可删除
            log.error("-->该资源已被使用，请先在角色中解除对该角色的使用");
        } else {
            resourceService.delete(resource);
        }
        return "redirect:/admin/resource/list";
    }
}
